package cn.glc.daily.life.common.exceptions;

import com.google.common.collect.Lists;
import org.springframework.core.MethodParameter;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * {@link Valid} 自定义注解
 *
 * @author simon
 * @date 2020/6/5 11:23
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
public class CustomMethodArgumentNotValidException extends MethodArgumentNotValidException {
    /**
     * Constructor for {@link MethodArgumentNotValidException}.
     *
     * @param parameter     the parameter that failed validation
     * @param bindingResult the results of the validation
     */
    public CustomMethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult) {
        super(parameter, bindingResult);
    }

    /**
     * 重写了 @valid 注解拦截异常的返回,现在每次只返回一个错误信息（主要是方便前端展示）
     *
     * @return
     */
    @Override
    public String getMessage() {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = Lists.newArrayList(getBindingResult().getAllErrors());
        if (!allErrors.isEmpty()) {
            Collections.sort(allErrors, Comparator.comparing(o -> ((FieldError) o).getField()));
            sb.append(allErrors.get(0).getDefaultMessage());
        }
        return sb.toString();
    }

    @Override
    public BindingResult getBindingResult() {
        return super.getBindingResult();
    }
}
